package com.dupf.product.rpc.service.impl;

import com.dupf.common.util.ItvJsonUtil;
import com.dupf.common.util.RedisUtil;
import com.dupf.product.common.constant.ProductConstant;
import com.fasterxml.jackson.core.type.TypeReference;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class QiniuUploadServiceImpl {
    private static final Logger LOGGER = LoggerFactory.getLogger(QiniuUploadServiceImpl.class);

    private static final Auth qiniuAuth = Auth.create(ProductConstant.QINIU_ACCESS_KEY, ProductConstant.QINIU_SECRET_KEY);

    public Map<String, Object> getUploadToken(String uid, String bucket, String module) {
        String cacheToken = RedisUtil.get(ProductConstant.UPLOAD_REDIS_PREFIX + "bucket:" + bucket);

        Map<String, Object> map = ItvJsonUtil.readValue(cacheToken, new TypeReference<Map<String, Object>>() {
        });

        if ((map == null) || (map.size() <= 0)) {
            long expires = ProductConstant.QINIU_TOKEN_EXPIRES;
            String uploadToken = qiniuAuth.uploadToken(bucket, null, expires, null);

            map = new HashMap<>();
            map.put("uploadToken", uploadToken);
            map.put("applyTime", System.currentTimeMillis() / 1000);
            map.put("expires", expires);

            if (ProductConstant.QINIU_BUCKET_VIDEO.equals(bucket)) {
                String auxiliaryBucket = ProductConstant.QINIU_BUCKET_PICTURE;
                String auxiliaryToken = qiniuAuth.uploadToken(auxiliaryBucket, null, expires, null);
                map.put("auxiliaryToken", auxiliaryToken);
            }

            RedisUtil.set(ProductConstant.UPLOAD_REDIS_PREFIX + "bucket:" + bucket, ItvJsonUtil.writeValue(map), ProductConstant.UPLOAD_REDIS_EXPIRE * 60);
        } else {
            int applyTime = (int) map.get("applyTime");
            int expires = (int) map.get("expires");
            int restExpires = expires + applyTime - (int) (System.currentTimeMillis() / 1000);
            map.put("expires", restExpires);
        }

        return map;
    }

    /**
     * 直接上传网络图片
     *
     * @param url
     * @param bucket
     * @return
     */
    public FetchRet uploadUrlFile(String url, String bucket, String key) {
        Auth auth = Auth.create(ProductConstant.QINIU_ACCESS_KEY, ProductConstant.QINIU_SECRET_KEY);
        BucketManager bm = new BucketManager(auth, new Configuration());
        try {
            return bm.fetch(url, bucket, key);
        } catch (QiniuException e) {
            LOGGER.error("上传网络图片到七牛云报错", e);
        }

        return null;
    }
}
